package com.life.notes.config.utils;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 树工具类
 * @author lishuqian
 * @date 2020/6/12
 */
public class TreeUtil {

    /**
     * 封装树
     *
     * @param parentList 要封装为树的父对象集合
     * @param originalList 原始list数据
     * @param keyName 作为唯一标示的字段名称
     * @param parentFieldName 模型中作为parent字段名称
     * @param childrenFieldName 模型中作为children的字段名称
     */
    public static <T,C> void fillTree(List<T> parentList, List<C> originalList, String keyName, String parentFieldName, String childrenFieldName) throws Exception {
        for (int i = 0; i < parentList.size(); i++) {
            List<C> children = fillChildren(parentList.get(i), originalList, keyName, parentFieldName, childrenFieldName);
            if (children.isEmpty()) {
                continue;
            }
            originalList.removeAll(children);
            fillTree(children, originalList, keyName, parentFieldName, childrenFieldName);
        }
    }

    /**
     * 封装子对象
     *
     * @param parent 父对象
     * @param originalList 待处理对象集合
     * @param keyName 作为唯一标示的字段名称
     * @param parentFieldName 模型中作为parent字段名称
     * @param childrenFieldName 模型中作为children的字段名称
     */
    private static <T,C> List<C> fillChildren(T parent, List<C> originalList, String keyName, String parentFieldName, String childrenFieldName) throws Exception {
        List<C> childList = new ArrayList<>();
        Object parentId = BeanUtil.getProperty(parent, keyName);
        for (int i = 0; i < originalList.size(); i++) {
            C t = originalList.get(i);
            Object childParentId = BeanUtil.getProperty(t, parentFieldName);
            if (parentId.equals(childParentId)) {
                childList.add(t);
            }
        }
        if (!childList.isEmpty()) {
            FieldUtils.writeDeclaredField(parent, childrenFieldName, childList, true);
        }
        return childList;
    }
}
